package com.redwood.report.net.download;

import android.widget.Toast;

import com.duowan.mobile.netroid.Listener;
import com.duowan.mobile.netroid.RequestQueue;
import com.duowan.mobile.netroid.request.FileDownloadRequest;
import com.duowan.mobile.netroid.toolbox.FileDownloader;
import com.redwood.report.MApplication;
import com.redwood.report.R;
import com.redwood.report.common.Constant;
import com.redwood.report.net.Netroid;
import com.redwood.report.util.Utils;

import java.io.File;

/**
 * Created by daiye on 2016/11/10 0010.
 */

public class DownloadManager {
    private static FileDownloader mDownloder;
    private static DownloadManager self = null;

    public static final int UPDATE = 1;

    public DownloadManager() {
        init();
    }

    public static DownloadManager getInstance() {
        if (null == self) {
            self = new DownloadManager();
        }
        return self;
    }

    private void init() {
        RequestQueue queue = Netroid.newRequestQueue(MApplication.getContext());
        mDownloder = new FileDownloader(queue, 1) {
            @Override
            public FileDownloadRequest buildRequest(String storeFilePath, String url) {
                return new FileDownloadRequest(storeFilePath, url) {
                    @Override
                    public void prepare() {
                        addHeader("Accept-Encoding", "identity");
                        super.prepare();
                    }
                };
            }
        };
        createFile();
    }

    private static void createFile() {
        File downloadDir = new File(Constant.SaveDirPath);
        if (!downloadDir.exists()) downloadDir.mkdir();
        File downloadApkDir = new File(Constant.SaveApkDirPath);
        if (!downloadApkDir.exists()) downloadApkDir.mkdir();
        if (new File(Constant.SaveAPkFile).exists())
            new File(Constant.SaveAPkFile).delete();
    }

    public static FileDownloader.DownloadController download(int type, String url, Listener<Void> listener) {
        FileDownloader.DownloadController controller = null;
        if (!Utils.sdacrdExist()) {
            Toast.makeText(MApplication.getContext(), MApplication.getInstance().getString(R.string.toast_sd_none), Toast.LENGTH_SHORT).show();
            return controller;
        }
        createFile();
        switch (type) {
            case UPDATE:
                controller = mDownloder.add(Constant.SaveAPkFile, url, listener);
                break;
        }
        return controller;
    }

    public static void clearAllDownloadTask() {
        mDownloder.clearAll();
    }
}